﻿using System;
using System.IO;
using System.Threading.Tasks;
using Eamon.MeituanDotnetSDK.api.common;
using Eamon.MeituanDotnetSDK.@enum;
using Eamon.MeituanDotnetSDK.exception;
using Eamon.MeituanDotnetSDK.httpclient;
using Eamon.MeituanDotnetSDK.utils;

namespace Eamon.MeituanDotnetSDK.executor
{
    public abstract class AbstractExecutor : Executor
    {
        protected OpenAPIHttpClient httpClient;
        protected abstract void prepare(ExecutionContext context);

        public AbstractExecutor()
        {
        }

        public Task<string> execute(ExecutionContext context)
        {
            prepare(context);
            return doExecute(context);
        }
        protected Task<string> doExecute(ExecutionContext context)
        {
            IAPI api = context.getApi();
            HttpMethodEnum method = api.getHttpMethod();

            string url = context.getUrl();
            try
            {
                if (HttpMethodEnum.GET == method)
                {
                    Task<string> result = httpClient.GetResponse(url, HttpMethodEnum.GET, context.getParams(), CancellationToken.None);
                    return result;
                }
                else
                {
                    Task<string> result = httpClient.GetResponse(url, HttpMethodEnum.POST, context.getParams(), CancellationToken.None);
                    return result;
                }
            }
            catch (IOException e)
            {
                throw new MtSdkException("do execute exception", e);
            }

        }
    }
}
